package com.jxc.action.kcgl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.jxc.action.BaseAction;
import com.jxc.model.vo.DataGrid;
import com.jxc.model.vo.Json;
import com.jxc.model.vo.SessionInfo;
import com.jxc.model.vo.VBrand;
import com.jxc.model.vo.VGoods;
import com.jxc.model.vo.VRepertory;
import com.jxc.model.vo.VTransferlist;
import com.jxc.model.vo.VTransferlistItem;
import com.jxc.model.vo.VUser;
import com.jxc.service.GoodsServiceI;
import com.jxc.service.RepertoryServiceI;
import com.jxc.service.TransferlistItemServiceI;
import com.jxc.service.TransferlistServiceI;
import com.jxc.service.UserServiceI;
import com.jxc.util.ExceptionUtil;
import com.jxc.util.ResourceUtil;
import com.opensymphony.xwork2.ModelDriven;

@Namespace("/kcgl")
@Action(value = "goodsTransferAction", results = { @Result(name = "goodsTransfer", location = "/amountRelate/goodsTransfer.jsp") })
public class GoodsTransferAction extends BaseAction implements ModelDriven<VTransferlist> {
	private final static Logger logger = LoggerFactory.getLogger(GoodsTransferAction.class);

	private VTransferlist model = new VTransferlist();
	private String items;

	@Autowired
	private TransferlistServiceI transferlistService;
	@Autowired
	private TransferlistItemServiceI transferlistItemService;
	@Autowired
	private UserServiceI userService;
	@Autowired
	private RepertoryServiceI repertoryService;
	@Autowired
	private GoodsServiceI goodsService;

	public String goodsTransfer() {
		getSubAuths("KCGL_KCDB");
		return "goodsTransfer";
	}

	public String goodsTransferItem() {
		return "goodsTransferItem";
	}

	public void datagrid() throws Exception {
		if (model.getBeginDate() != null) {
			String beginDateStr = new SimpleDateFormat("yyyy-MM-dd").format(model.getBeginDate());
			model.setBeginDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(beginDateStr + " 00:00:00"));
		}
		if (model.getEndDate() != null) {
			String endDateStr = new SimpleDateFormat("yyyy-MM-dd").format(model.getEndDate());
			model.setEndDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endDateStr + " 23:59:59"));
		}
		if (model.getOrid() != null) {
			this.writeJson(transferlistService.datagrid(model));
		} else {
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
			VUser vuser = userService.get(sessionInfo.getUserId());
			if (vuser.getReid() != null) {
				model.setOrid(vuser.getReid());
				this.writeJson(transferlistService.datagrid(model));
			} else {
				VRepertory vrepertory = new VRepertory();
				vrepertory.setUid(sessionInfo.getUserId());
				List<VRepertory> vrepertories = repertoryService.list(vrepertory);
				if (vrepertories != null && vrepertories.size() > 0) {
					List<VBrand> rows = new ArrayList<VBrand>();
					Map<String, Integer> serialMap = new HashMap<String, Integer>();
					Long total = 0l;
					for (VRepertory vre : vrepertories) {
						model.setOrid(vre.getId());
						DataGrid subDg = transferlistService.datagrid(model);
						for (Iterator<VTransferlist> it = subDg.getRows().iterator(); it.hasNext();) {
							VTransferlist vt = it.next();
							if (serialMap.get(vt.getSerial()) == null) {
								serialMap.put(vt.getSerial(), 1);
							} else {
								it.remove();
								subDg.setTotal(subDg.getTotal() - 1);
							}
						}
						rows.addAll(subDg.getRows());
						total += subDg.getTotal();
					}
					DataGrid totalDg = new DataGrid();
					totalDg.setRows(rows);
					totalDg.setTotal(total);
					this.writeJson(totalDg);
				} else {
					DataGrid dg = new DataGrid();
					dg.setTotal(0l);
					dg.setRows(new ArrayList<VBrand>());
					this.writeJson(dg);
				}
			}
		}
	}

	public void noAuth_search() {
		this.writeJson(this.transferlistService.search(model));
	}

	/**
	 * 库存调拔单添加
	 */
	public void add() {
		// TODO 判断调出库存是否有足够的库存量
		Json j = new Json();
		try {
			model.setIsOutConfirm(false);
			model.setIsInConfirm(false);
			int total = 0;
			Map<Long, VTransferlistItem> itemMap = new HashMap<Long, VTransferlistItem>();
			List<VTransferlistItem> vtlis = new ArrayList<VTransferlistItem>();
			if (StringUtils.isNotBlank(items)) {
				String[] itemInfos = items.split(",");
				for (int i = 0; i < itemInfos.length; i++) {
					String goodsId = itemInfos[i];
					i++;
					String num = itemInfos[i];
					total += Integer.parseInt(num);
					VTransferlistItem vtli = itemMap.get(Long.parseLong(goodsId));
					if (vtli == null) {
						vtli = new VTransferlistItem();
						vtli.setGid(Long.parseLong(goodsId));
						vtli.setNum(Integer.parseInt(num));
						vtlis.add(vtli);
					} else {
						vtli.setNum(vtli.getNum() + Integer.parseInt(num));
					}
					itemMap.put(Long.parseLong(goodsId), vtli);
				}
			}
			model.setNum(total);
			Long tlid = transferlistService.save(model);
			transferlistItemService.batchSave(vtlis, tlid);
			j.setMsg("添加成功！");
			j.setSuccess(true);
		} catch (Exception e) {
			j.setMsg("添加失败！");
			logger.info(ExceptionUtil.getExceptionMessage(e));
		}
		super.writeJson(j);
	}

	/**
	 * 修改调拔单
	 * 
	 */
	public void edit() {
		Json j = new Json();
		try {
			transferlistService.update(model);
			j.setSuccess(true);
			j.setMsg("编辑成功！");
		} catch (Exception e) {
			logger.error(ExceptionUtil.getExceptionMessage(e));
			j.setMsg("编辑失败！");
		}
		super.writeJson(j);
	}

	/**
	 * 删除调拔单
	 * 
	 */
	public void delete() {
		// TODO 判断要删除的调拔单中是否已经确认过，只有未确认过的调拔单才能删除
		Json j = new Json();
		transferlistService.delete(model.getIds());
		j.setSuccess(true);
		j.setMsg("删除成功!");
		super.writeJson(j);
	}

	/**
	 * 确认调出调拔单
	 * 
	 */
	public void outConfirm() {
		Json j = new Json();
		SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
		List<VTransferlist> vtls = transferlistService.combobox(model);
		VTransferlist vtl = vtls.get(0);
		if (vtl.getIsOutConfirm()) {
			j.setMsg("该调拔单已被确认！");
		} else {
			vtl.setOcuid(sessionInfo.getUserId());
			vtl.setOutConfirmDate(new Date());
			vtl.setIsOutConfirm(true);
			transferlistService.update(vtl);

			VTransferlistItem param = new VTransferlistItem();
			param.setTlid(model.getId());
			List<VTransferlistItem> items = transferlistItemService.combobox(param);
			for (VTransferlistItem item : items) {
				VGoods vgParam = new VGoods();
				vgParam.setId(item.getGid());
				List<VGoods> vgs = goodsService.combobox(vgParam);
				if (vgs.size() > 0) {
					VGoods vg = vgs.get(0);
					vg.setAmount(vg.getAmount() - item.getNum());
					vg.setTransferTotal(vg.getTransferTotal()+item.getNum());
					goodsService.update(vg);
				}
			}

			j.setMsg("确认成功!");
		}
		j.setSuccess(true);
		super.writeJson(j);
	}

	/**
	 * 确认调入调拔单
	 * 
	 */
	public void inConfirm() {
		Json j = new Json();
		SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
		List<VTransferlist> vtls = transferlistService.combobox(model);
		VTransferlist vtl = vtls.get(0);
		if (vtl.getIsInConfirm()) {
			j.setMsg("该调拔单已被确认!");
		} else {
			vtl.setIcuid(sessionInfo.getUserId());
			vtl.setInConfirmDate(new Date());
			vtl.setIsInConfirm(true);
			transferlistService.update(vtl);

			VTransferlistItem param = new VTransferlistItem();
			param.setTlid(model.getId());
			List<VTransferlistItem> items = transferlistItemService.combobox(param);
			for (VTransferlistItem item : items) {
				VGoods vgParam = new VGoods();
				vgParam.setId(item.getGid());
				List<VGoods> vgs = goodsService.combobox(vgParam);
				if (vgs.size() > 0) {
					VGoods vg = vgs.get(0);
					VGoods vgParam2 = new VGoods();
					vgParam2.setRid(vtl.getIrid());
					vgParam2.setBarcode(vg.getBarcode());
					List<VGoods> vgs2 = goodsService.search(vgParam2);
					if (vgs2.size() > 0) {
						VGoods vg2 = vgs2.get(0);
						vg2.setAmount(vg2.getAmount() + item.getNum());
						vg2.setTransferTotal(vg2.getTransferTotal()+item.getNum());
						goodsService.update(vg2);
					} else {
						VGoods copyVg = new VGoods();
						BeanUtils.copyProperties(vg, copyVg);
						copyVg.setRid(vtl.getIrid());
						copyVg.setAmount(item.getNum());
						copyVg.setTransferTotal(copyVg.getTransferTotal()+item.getNum());
						goodsService.save(copyVg);
					}
				}
			}

			j.setMsg("确认成功!");
		}
		j.setSuccess(true);
		super.writeJson(j);
	}

	@Override
	public VTransferlist getModel() {
		return model;
	}

	public String getItems() {
		return items;
	}

	public void setItems(String items) {
		this.items = items;
	}

}
